package com.svo.weitu.model.push;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.text.TextUtils;
import android.util.Log;

import com.svo.platform.picbrowser.PicBrowseActivity;
import com.svo.weitu.R;
import com.svo.weitu.activity.MainActivity;
import com.svo.weitu.activity.PicBrowser;
import com.svo.weitu.util.Cons;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;

import cn.jpush.android.api.JPushInterface;

/**
 * Push消息处理receiver
 */
public class PushReceiver extends BroadcastReceiver {
	private static final String TAG = "PushReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
		Log.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "接收Registration Id : " + regId);
            //send the Registration Id to your server...
        }else if (JPushInterface.ACTION_UNREGISTER.equals(intent.getAction())){
        	String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "接收UnRegistration Id : " + regId);
          //send the UnRegistration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
        	Log.d(TAG, "接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
//        	processCustomMessage(context, bundle);
        	String title = intent.getExtras().getString(JPushInterface.EXTRA_MESSAGE);
        	if (TextUtils.isEmpty(title)) {
				return;
			}
            NotificationManagerCompat manager = NotificationManagerCompat.from(context);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.setDefaults(Notification.DEFAULT_ALL);
            builder.setSmallIcon(R.drawable.logo);
            builder.setAutoCancel(true);
            builder.setContentTitle("唯图");
            builder.setContentText(title);

    		Intent i = new Intent(JPushInterface.ACTION_NOTIFICATION_OPENED);
    		i.putExtras(intent.getExtras());
    		i.addCategory("com.svo.weitu");
    		PendingIntent contentIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(contentIntent);
            Notification notification=builder.build();
            manager.notify((int) (System.currentTimeMillis()/10000),notification);
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d(TAG, "接收到推送下来的通知的ID: " + notifactionId);
        	
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "用户点击打开了通知:"+intent.getExtras().getString(JPushInterface.EXTRA_NOTIFICATION_TITLE)+";"+intent.getExtras().getString(JPushInterface.EXTRA_ALERT));
        	
        	String content = intent.getExtras().getString(JPushInterface.EXTRA_EXTRA);
			String urls = null;
			try {
				JSONObject contentJson = new JSONObject(content);
				urls = contentJson.getString("pics").trim();
			} catch (Exception e) {
				Log.d(TAG, "parse message as json exception " + e);
				return;
			}
			String[] arr = urls.split(";");
			ArrayList<String> pics = (ArrayList<String>) Arrays.asList(arr);
			Intent aIntent = new Intent(context, PicBrowser.class);
			aIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			aIntent.putExtra(PicBrowseActivity.PICS, pics);
			aIntent.putExtra("title", intent.getExtras().getString(JPushInterface.EXTRA_MESSAGE));
			aIntent.putExtra("subContent", intent.getExtras().getString(JPushInterface.EXTRA_MESSAGE));
			intent.putExtra("url", Cons.gen+"jsp/wx_link.jsp?pics="+pics.get(0));
			Intent homeIntent = new Intent(context, MainActivity.class);
			homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(homeIntent);
			context.startActivity(aIntent);
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
        } else {
        	Log.d(TAG, "Unhandled intent - " + intent.getAction());
        }
	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}
	
	//send msg to MainActivity
	/*private void processCustomMessage(Context context, Bundle bundle) {
		if (MainActivity.isForeground) {
			String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
			Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
			msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
			if (!ExampleUtil.isEmpty(extras)) {
				try {
					JSONObject extraJson = new JSONObject(extras);
					if (null != extraJson && extraJson.length() > 0) {
						msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
					}
				} catch (JSONException e) {

				}

			}
			context.sendBroadcast(msgIntent);
		}
	}*/
	/*@Override
	public void onReceive(final Context context, Intent intent) {

		Log.d(TAG, ">>> Receive intent: \r\n" + intent);

		if (intent.getAction().equals(PushConstants.ACTION_MESSAGE)) {
			//获取消息内容
			String message = intent.getExtras().getString(
					PushConstants.EXTRA_PUSH_MESSAGE_STRING);

			//消息的用户自定义内容读取方式
			Log.i(TAG, "onMessage: " + message);
			
			//自定义内容的json串
        	Log.d(TAG, "EXTRA_EXTRA = " + intent.getStringExtra(PushConstants.EXTRA_EXTRA));
			

			//用户在此自定义处理消息,以下代码为demo界面展示用
			Intent responseIntent = null;
			responseIntent = new Intent(Utils.ACTION_MESSAGE);
			responseIntent.putExtra(Utils.EXTRA_MESSAGE, message);
			responseIntent.setClass(context, MainActivity.class);
			responseIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(responseIntent);

		} else if (intent.getAction().equals(PushConstants.ACTION_RECEIVE)) {
			
		//可选。通知用户点击事件处理
		} else if (intent.getAction().equals(PushConstants.ACTION_RECEIVER_NOTIFICATION_CLICK)) {
//			Log.d(TAG, "intent=" + intent.toUri(0));
			Log.d(TAG, "userId:" + intent.getExtras().getString(PushConstants.EXTRA_USER_ID));
			//自定义内容的json串
//        	Log.d(TAG, "EXTRA_EXTRA = " + intent.getStringExtra(PushConstants.EXTRA_EXTRA));
			String content = intent.getExtras().getString(PushConstants.EXTRA_EXTRA);
			String urls = null;
			try {
				JSONObject contentJson = new JSONObject(content);
				urls = contentJson.getString("pics");
			} catch (JSONException e) {
				Log.d(TAG, "parse message as json exception " + e);
			}
			String[] arr = urls.split(";");
			ArrayList<String> pics = (ArrayList<String>) Util.stringsToList(arr);
			Intent aIntent = new Intent(context, PicBrowser.class);
			aIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			aIntent.putExtra(PicBrowseActivity.PICS, pics);
			aIntent.putExtra("title", intent.getExtras().getString(PushConstants.EXTRA_NOTIFICATION_TITLE));
			aIntent.putExtra("subContent", intent.getExtras().getString(PushConstants.EXTRA_NOTIFICATION_CONTENT));
			intent.putExtra("url", Cons.gen+"jsp/wx_link.jsp?pics="+pics.get(0));
			Intent homeIntent = new Intent(context, MainActivity.class);
			homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(homeIntent);
			context.startActivity(aIntent);
		}
	}*/

}
